package com.onstar.cn.common.util;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

import com.onstar.cn.common.log.LogManager;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.regex.Pattern;

public class CommonUtil {
    private static Pattern phoneValidate = Pattern.compile("^[0-9]*$");
    private static Pattern inputer = Pattern.compile("^[A-Za-z0-9]+$");
    public static Pattern inputer_user_name = Pattern.compile("^(?![0-9]+$)[0-9A-Za-z]{6,20}$");
    private static Pattern inputer_include_blank = Pattern.compile("^[A-Za-z0-9\\s]+$");
    private static Pattern emailer = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
    private static Pattern passwordValidate2 = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,25}$");
    private static Pattern viner = Pattern.compile("^[A-Za-z0-9]{17}$");
    private static Pattern postcodeValidate = Pattern.compile("^[0-9]{6}$");
    private static Pattern plate_number = Pattern.compile("^[\u4e00-\u9fa5]{1}[A-Z_0-9]{6,7}$");

    /**
     * @param @param  plateNumber
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: isPlateNumber
     * @Description: 验证车牌号
     */
    public static boolean isPlateNumber(String plateNumber) {
        if (isNull(plateNumber)) {
            return false;
        }
        return plate_number.matcher(plateNumber).matches();
    }

    /**
     * @param @param  email
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: isEmail
     * @Description: 验证邮箱
     */
    public static boolean isEmail(String email) {
        if (isNull(email)) {
            return false;
        }
        // email.replace(oldChar, newChar)
        return emailer.matcher(email).matches();
    }

    /**
     * @param @param  phone
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: isPhone
     * @Description: 验证手机号
     */
    public static boolean isPhone(String phone) {
        if (!isNull(phone)) {
            if (phone.length() == 11) {
                return phoneValidate.matcher(phone).matches();
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * @param @param  password
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: passwordValidate
     * @Description: 验证密码
     */
    public static boolean passwordValidate(String password) {
        if (isNull(password)) {
            return false;
        }
        return passwordValidate2.matcher(password).matches();
    }

    public static boolean isInt(String arg) {
        if (arg == null)
            return false;
        try {
            Integer.valueOf(arg);
            return true;
        } catch (NumberFormatException e) {
        }
        return false;
    }

    /**
     * @param @param  value
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: isNull
     * @Description: 是否为null
     */
    public static boolean isNull(String value) {
        return (value == null) || ("".equals(value.trim())) || ("null").equals(value.trim());
    }

    public static boolean isNull(Object value) {
        if (value == null) {
            return true;
        }
        if (value instanceof String) {
            return isNull(value + "");
        }
        return false;
    }

    public static int dp2px(int dp, Context context) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                context.getResources().getDisplayMetrics());
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    public static boolean isDouble(String arg) {
        if (arg == null)
            return false;
        try {
            Double.valueOf(arg);
            return true;
        } catch (NumberFormatException e) {
        }
        return false;
    }



    /**
     * @param @param imageView    设定文件
     * @return void    返回类型
     * @throws
     * @Title: showLoadingAnim
     * @Description: 显示Loading动画
     */
    public static void showLoadingAnim(ImageView imageView) {
        if (imageView == null) {
            return;
        }
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getBackground();
        if (animationDrawable != null)
            animationDrawable.start();
    }

    /**
     * @param @param  input
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: checkInput
     * @Description: Input格式
     */
    public static boolean checkInput(String input) {
        return inputer.matcher(input).matches();
    }

    /**
     * @param @param  input
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: checkInput
     * @Description: 6-18位，不能纯数字，可以纯字母，字母数字组合
     */
    public static boolean checkUsername(String input) {
        String regex = "^(?![0-9]+$)[0-9A-Za-z]{6,20}$";
//		String regex = "^[A-Za-z0-9]+$";
//		String regex = "(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,20})$";
        return input.matches(regex);
    }

    /**
     * @param @param  input
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: checkInputIncludeBlank
     * @Description: 格式包含空格
     */
    public static boolean checkInputIncludeBlank(String input) {
        return inputer_include_blank.matcher(input).matches();
    }

    public static void dismissLoadingAnim(ImageView imageView) {
        if (imageView == null) {
            return;
        }
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getBackground();
        if (animationDrawable != null)
            animationDrawable.stop();
        BitmapUtil.recycleImageView(imageView);
    }

    /**
     * @param @param  file
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: deleteFile
     * @Description: 删除文件
     */
    public static boolean deleteFile(File file) {
        try {
            //判断文件是否存在
            if (file.exists()) {
                if (file.isFile()) {
                    file.delete();
                } else if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFile(files[i]);
                    }
                } else {
                    file.delete();
                }
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param @param content
     * @param @param context    设定文件
     * @return void    返回类型
     * @throws
     * @Title: copy
     * @Description: 拷贝文字
     */
    public static void copy(String content, Context context) {
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        clipboardManager.setPrimaryClip(ClipData.newPlainText(null, content));
    }


    /**
     * @param @param  f
     * @param @return 设定文件
     * @return long    返回类型
     * @throws
     * @Title: getFileSize
     * @Description: 获取文件大小
     */
    public static long getFileSize(File f) {
        try {
            long size = 0;
            File flist[] = f.listFiles();
            // if(flist==null)return 0;
            for (int i = 0; i < flist.length; i++) {
                if (flist[i].isDirectory()) {
                    size = size + getFileSize(flist[i]);
                } else {
                    size = size + flist[i].length();
                }
            }
            return size;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    private static double getFileSize(long fileSize) {
        // 1M=1024KB,1KB=1024B
        return (double) fileSize / 1048576;
    }

    public static void removeMapCache(File file) {
        LogManager.getInstance().d("file.length(): " + getFileSize(getFileSize(file)));

        if (file != null && file.exists() && getFileSize(getFileSize(file)) > 50) {
            deleteFile(file);
        }
    }

    /**
     * @param @param context
     * @param @param editText    设定文件
     * @return void    返回类型
     * @throws
     * @Title: hideKeyBoard
     * @Description: 隐藏键盘
     */
    public static void showKeyBoard(Activity context, EditText editText) {
        if (context == null) {
            return;
        }
        InputMethodManager mInputMethodManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        mInputMethodManager.showSoftInputFromInputMethod(editText.getWindowToken(), 0);
    }

    /**
     * @param @param  context
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: checkNetWorkState
     * @Description: 检查网络
     */
    public static void hideKeyBoard(Activity context, EditText editText) {
        if (context == null) {
            return;
        }
        InputMethodManager mInputMethodManager = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        mInputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    public static boolean isVin(String vin) {
        return viner.matcher(vin).matches();
    }

    public static long formatDate(String dateStr) {
        if (dateStr.contains("+")) {
            dateStr = dateStr.substring(0, dateStr.indexOf("+"));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        try {
            return sdf.parse(dateStr + " 00:00").getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * @param @param  str
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: removeSpecialCharacters
     * @Description: 特殊字符替换
     */
    public static boolean checkNetWorkState(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService("connectivity");
        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        if (null != networkInfo) {
            return networkInfo.isAvailable();
        } else {
            return false;
        }
    }


    /**
     * @param @param  str
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: removeSpecialCharacters
     * @Description: 特殊字符替换
     */
    public static String removeSpecialCharacters(String str) {
        return str.replace("+", "").replace("-", "").replace(" ", "").replace("&", "").replace("*", "")
                .replace("#", "").replace("@", "").replace("!", "").replace("_", "").replace("=", "").replace("(", "")
                .replace(")", "").replace("^", "").replace("$", "");
    }

    /**
     * @param @param  emailOrPhone
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: isEmailOrPhone
     * @Description: 验证
     */
    public static boolean isEmailOrPhone(String emailOrPhone) {
        if (isNull(emailOrPhone)) {
            return false;
        }
        return isEmail(emailOrPhone) || isPhone(emailOrPhone);
    }

    /**
     * @param @param  str
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: isNumber
     * @Description: 验证是否是数字
     */
    public static boolean isNumber(String str) {
        return str.matches("[0-9]+");
    }

    /**
     * @param @param  postCode
     * @param @return 设定文件
     * @return boolean    返回类型
     * @throws
     * @Title: isPostCode
     * @Description: 验证
     */
    public static boolean isPostCode(String postCode) {
        if (isNull(postCode)) {
            return false;
        }
        return postcodeValidate.matcher(postCode).matches();
    }

    /**
     * @param @param  str
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: returnFormatString
     * @Description: 字符串转换
     */
    public static String returnFormatString(String str) {
        return String.format("%.2f", Double.parseDouble(str));
    }

    /**
     * @param @param  str
     * @param @param  isEmail
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: replaceString
     * @Description: 替换字符串
     */
    public static String replaceString(String str, boolean isEmail) {
        if (CommonUtil.isNull(str)) {
            return "";
        }
        String returnStr = "";
        try {
            if (isEmail) {
                String temp = str.substring(0, str.indexOf("@"));
                if (temp.length() < 4) {
                    temp = temp.replace(temp.substring(temp.length() - 1, temp.length()), "*");
//                    temp = "****";
                } else {
                    temp = temp.substring(0,temp.length()-3)+"***";
//                    temp = temp.replace(temp.substring(temp.length() - 3, temp.length()), "***");
                }
                returnStr = temp + str.substring(str.indexOf("@"), str.length());
            } else {
                returnStr = str.substring(0, 3) + "****" + str.substring(7, 11);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnStr;
    }

    /**
     * @param @param  str
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: returnFormatString
     */
    public static String returnFormatString(double str) {
        if (isNull(str)) {
            return "";
        }
        return String.format("%.2f", str);
    }

    /**
     * ‘@’前面不足四位则用字符第一位+“****”标示
     *
     * @param str
     * @param isEmail
     * @return
     */
    public static String replaceEmail(String str, boolean isEmail) {
        if (CommonUtil.isNull(str)) {
            return "";
        }
        String returnStr = "";
        try {
            if (isEmail) {
                String temp = str.substring(0, str.indexOf("@"));
                if (temp.length() < 4) {
                    temp = temp.replace(temp.substring(temp.length() - 1, temp.length()), "*");
//                    temp = str.substring(0, 1) + "****";
                } else {
                    temp = temp.replace(temp.substring(temp.length() - 3, temp.length()), "***");
                }
                returnStr = temp + str.substring(str.indexOf("@"), str.length());
            } else {
                returnStr = str.substring(0, 3) + "****" + str.substring(7, 11);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnStr;

    }

    /**
     * 讲json字符串转换成string 数组，前提是此json string格式：["a","b"]
     *
     * @param str
     * @return
     */
    public static String[] switchToStringArray(String str) {
        if (str.contains("[") && str.contains("]")) {
            str = str.replace("[", "").replace("]", "");
            String[] strArray = str.split(",");
            return strArray;
        }
        return null;
    }

    /**
     * 将登录名使用****隐藏中间的一些字符信息
     *
     * @param loginName
     * @return
     */
    public static String maskLoginName(String loginName) {
        if (isNull(loginName)) return "";
        StringBuilder sb = new StringBuilder();
        sb.append(loginName.substring(0, 3)).append("****").append(loginName.substring(loginName.length() - 3));
        return sb.toString();
    }


    /**
     * 将登录名使用****隐藏中间的一些字符信息
     *
     * @param input
     * @return
     */
    public static String maskWithStar(String input, int headIndex, int tailIndex) {
        if (isNull(input)) return "";
        StringBuilder sb = new StringBuilder();
        sb.append(input.substring(0, headIndex)).append("****").append(input.substring(input.length() - tailIndex));
        return sb.toString();
    }
    /**
     * 将登录名使用****隐藏中间的一些字符信息
     *
     * @param input
     * @return
     */
    public static String maskWithAllStar(String input, int headIndex, int tailIndex) {
        if (isNull(input)) return "";
        int len = input.length();
        if(len<=headIndex || len<=tailIndex)
            return input;
        StringBuilder sb = new StringBuilder();
       if(len > headIndex + tailIndex){
           int difLen = len - (headIndex+tailIndex);
           sb.append(input.substring(0, headIndex));
           while (difLen >0){
               sb.append("*");
               difLen -= 1;
           }
           sb.append(input.substring(len - tailIndex));
       }else{
           sb.append(input.substring(0, headIndex)).append("****").append(input.substring(input.length() - tailIndex));
       }
        return sb.toString();
    }

    public static String getDigit(String origin) {
        String numInStr = "";
        if (origin != null && !"".equals(origin)) {
            for (int i = 0; i < origin.length(); i++) {
                if (origin.charAt(i) >= 48 && origin.charAt(i) <= 57) {
                    numInStr += origin.charAt(i);
                } else {
                    return numInStr;
                }
            }
        }
        return numInStr;
    }

    public static void recycleAnimation(ImageView img, Animation animation) {
        if (img != null) {
            if (animation != null) {
                animation.reset();
                animation.cancel();
            }
            img.clearAnimation();
            img.setImageDrawable(null);
            img.setVisibility(View.INVISIBLE);
        }
    }

    public static Bitmap getScreenShoot(Activity activity) {
        // 获取windows中最顶层的view
        View view = activity.getWindow().getDecorView();
        view.buildDrawingCache();

        // 获取状态栏高度
        Rect rect = new Rect();
        view.getWindowVisibleDisplayFrame(rect);
        int statusBarHeights = rect.top;
        int titleHeight = dp2px(48, activity);
        Display display = activity.getWindowManager().getDefaultDisplay();

        // 获取屏幕宽和高
        int widths = display.getWidth();
        int heights = display.getHeight();

        // 允许当前窗口保存缓存信息
        view.setDrawingCacheEnabled(true);

        // 去掉状态栏
        Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
                statusBarHeights + titleHeight, widths, heights - statusBarHeights);

        // 销毁缓存信息
        view.destroyDrawingCache();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 10, bos);
        byte[] bytes = bos.toByteArray();
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 2;
        bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,opts);
        return bmp;
    }

    public static String getFilePath(Context context) {
        String filePath = "";
        if (!CommonUtil.isNull(Environment.getExternalStorageState()) && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            filePath = "/mnt/sdcard" + File.separator + "onstar";
        } else {
            filePath = context.getApplicationContext().getCacheDir().getAbsolutePath() + File.separator + "onstar";
        }
        File file = new File(filePath + File.separator);
        if (!file.exists()) {
            file.mkdirs();
        }
        return filePath;
    }


    /**
     * 匹配正数
     * @param str
     * @return
     */
    public static boolean isNumerice(String str) {
        if (!CommonUtil.isNull(str)) {
            Pattern pattern = Pattern.compile("[0-9.]*");
            return pattern.matcher(str).matches();
        } else {
            return false;
        }
    }

    /**
     * 匹配全数值
     * @param str
     * @return
     */
    public static boolean isAllNumerice(String str) {
        if (!CommonUtil.isNull(str)) {
            Pattern pattern = Pattern.compile("-?[0-9.]*");
            return pattern.matcher(str).matches();
        } else {
            return false;
        }
    }

    public static void jumpAndroidMarket(Context context) {
        Uri uri = Uri.parse("market://details?id=com.shanghaionstar");
//        context.startActivity(new Intent("android.intent.action.VIEW", uri));

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(uri); //跳转到应用市场，非Google Play市场一般情况也实现了这个接口

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
